package com.cupk.inspection.service;

import com.cupk.inspection.model.User;
import com.cupk.inspection.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    // 添加用户
    public User addUser(User user) {
        // 设置创建时间
        user.setCreated_at(new java.sql.Timestamp(System.currentTimeMillis()));
        return userRepository.save(user);
    }

    // 查询用户
    public Optional<User> selectUser(Long id) {
        return userRepository.findById(id);
    }

    // 删除用户
    public void deleteUser(Long id) {
        userRepository.deleteById(id);
    }

    // 更新用户
    public User updateUser(Long id, User user) {
        Optional<User> existingUser = userRepository.findById(id);
        if (existingUser.isPresent()) {
            User target = existingUser.get();
            target.setUsername(user.getUsername());
            target.setPassword(user.getPassword());
            target.setRole(user.getRole());
            return userRepository.save(target); // 保留原有 created_at
        }
        return null;
    }

    // 验证用户是否存在
    public boolean existsById(Long id) {
        return userRepository.existsById(id);
    }
    // 获取用户列表
    public List<User> getAllUsers() {
        return userRepository.findAll();
    }
    // 验证用户名是否存在
    public boolean existsByUsername(String username) {
        return userRepository.existsByUsername(username);
    }

    // 通过用户名查询用户
    public Optional<User> selectUserByUsername(String username) {
        return userRepository.findByUsername(username);
    }
}